
// 封装电梯导航函数
const listNum = document.querySelector('.listNum')
function elevator() {
  // 3. 导航渲染及跳转功能
  // 导航渲染
  listNum.innerHTML += questionList.map((item, i) => {
    return `<li class=" " data-id="${i}">${item.id}</li>`
  }).join('')

  // 电梯导航功能
  listNum.addEventListener('click', (e) => {
    // console.log(e.target.tagName)
    // console.log(e.target.dataset.id)
    if (e.target.tagName === 'LI' && e.target.dataset.id) {
      // 页面样式
      const old = document.querySelector('.listNum .current')
      if (old) old.classList.remove('current')
      e.target.classList.add('current')
      // 页面跳转
      const h3 = document.querySelector(`div[data-id="${e.target.dataset.id}"]`)
      if (h3) h3.scrollIntoView({ behavior: 'smooth', block: 'start' })
    }
  })
}
elevator()


function examClick(event) {
  if (event.target.tagName === 'SPAN' && event.target.classList.contains('num_option')) {
    const form = event.target.closest('form')
    Array.from(form.querySelectorAll('.num_option')).forEach(item => {
      item.classList.remove('active')
    })
    event.target.classList.add('active')

    // 存储答案到本地
    const question = event.target.closest('div.question')
    const questionIndex = question.dataset.id
    if (questionIndex) {
      const answer = event.target.textContent
      localStorage.setItem(`answered_${questionIndex}`, answer)
    }

    // // 高亮题目对应电梯导航序号颜色
    highHlight(questionIndex)
  }
}

// 绑定examClick事件
// onclick = "examClick(event)"
const answers = document.querySelectorAll('.answer')
answers.forEach(item => {
  item.addEventListener('click', examClick)
})

// 高亮电梯导航颜色
function highHlight(index) {
  const navItem = document.querySelector(`.listNum li[data-id="${index}"]`)
  if (navItem) {
    navItem.classList.add('active')
  }
}


const forms = document.querySelectorAll('form')
// 封装防丢失函数
function restoreAnswers() {
  // 5. 页面刷新答案不丢失功能
  // 获取所有表单元素
  // console.log(forms)
  forms.forEach((form) => {

    // 获取题目索引
    const questionIndex = form.parentElement.getAttribute('data-id');

    // 检查localStorage中是否有该题目的答案
    const userAnswer = localStorage.getItem(`answered_${questionIndex}`);
    // console.log(questionIndex, userAnswer)

    // 卷面恢复
    if (userAnswer) {
      // 如果有答案，找到对应的选项并设置为选中状态
      const options = form.querySelectorAll('.num_option')
      const optionToSelect = Array.from(options).find(item => item.textContent === userAnswer)
      if (optionToSelect) {
        optionToSelect.classList.add('active');
      }

      // 电梯导航恢复
      highHlight(questionIndex)
    }

  })
}
// 在页面加载时调用restoreAnswers函数
document.addEventListener('DOMContentLoaded', restoreAnswers);
